package com.heyige.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;

/**
 * 邮件配置类
 */
@Configuration
public class EmailConfig {
    
    private final AppConfig appConfig;
    
    public EmailConfig(AppConfig appConfig) {
        this.appConfig = appConfig;
    }
    
    /**
     * 配置JavaMailSender
     * @return JavaMailSender实例
     */
    @Bean
    public JavaMailSender javaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        
        // 获取邮件配置
        AppConfig.EmailConfig emailConfig = appConfig.getEmail();
        
        if (emailConfig == null) {
            throw new RuntimeException("邮件配置未找到，请检查application.yml配置文件");
        }
        
        // 设置邮件服务器配置
        mailSender.setHost(emailConfig.getHost());
        mailSender.setPort(emailConfig.getPort());
        mailSender.setUsername(emailConfig.getUsername());
        mailSender.setPassword(emailConfig.getPassword());
        mailSender.setProtocol(emailConfig.getProtocol() != null ? emailConfig.getProtocol() : "smtp");
        
        // 设置邮件属性
        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.debug", "false");
        
        // 如果启用了SSL，配置SSL属性
        if (Boolean.TRUE.equals(emailConfig.getSslEnabled())) {
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.fallback", "false");
        }
        
        return mailSender;
    }
}